//
//  LGRevisePhoneController.m
//  BreathTrainingTool
//
//  Created by 1234 on 2024/5/21.
//  修改手机号

#import "LGRevisePhoneController.h"

@interface LGRevisePhoneController ()
/**   */
@property (nonatomic , strong)UILabel *titleLabel1;
/**   */
@property (nonatomic , strong)UILabel *titleLabel2;
/**   */
@property (nonatomic , strong)UITextField *phoneTF;
/**   */
@property (nonatomic , strong)UITextField *codeTF;
/**   */
@property (nonatomic , strong)UIButton *codeBtn;
/**   */
@property (nonatomic , strong)UIButton *actionBtn;
/**   */
@property (nonatomic , strong)NSTimer *timer;
/**   */
@property (nonatomic , assign)NSInteger seconds;
/**   */
@property (nonatomic , copy)NSString *smsid;
/**   */
@property (nonatomic , assign)BOOL checked;

@end

@implementation LGRevisePhoneController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.checked = NO;
    self.title = @"更换手机号";
    [self createSubView];
    if (self.currentPhone.length>0) {
        NSString *phone = [self.currentPhone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        self.titleLabel1.text = [NSString stringWithFormat:@"请输入%@",phone];
    }
    
}
-(void)setCurrentPhone:(NSString *)currentPhone{
    _currentPhone = currentPhone;
}


//获取验证码
-(void)getSmsCodeAction:(UIButton *)sender{
    NSString *phoneNum = [self.phoneTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if([self checkTelNumber:phoneNum] == NO){
        [TooltipView showMessage:@"请输入正确的手机号" offset:0];
        return;
    }
    [RequestUtil withPOST:@"/brbot-resource/sms/endpoint/send-validate" parameters:@{@"phone":phoneNum} header:NO success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.smsid = LGNSString(returnData[@"id"]);
            self.seconds = 60;
            [self.timer invalidate];
            self.timer = nil;
            self.codeBtn.selected = YES;
            self.codeBtn.userInteractionEnabled = NO;
            self.codeBtn.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(120), 0, viewPix(120), viewPix(56));
            [self.codeBtn setTitle:[NSString stringWithFormat:@"重新发送(%ld)",self.seconds] forState:UIControlStateNormal];
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

//验证码倒计时
-(void)countDownAction{
    self.seconds--;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"重新发送(%ld)",self.seconds] forState:UIControlStateNormal];
    if (self.seconds == 0) {
        self.codeBtn.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(100), 0, viewPix(100), viewPix(56));
        self.codeBtn.selected = NO;
        self.codeBtn.userInteractionEnabled = YES;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
    }
}

//判断手机格式
- (BOOL)checkTelNumber:(NSString *)telNumber{
    NSString *pattern = @"^1+[0123456789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}

-(void)textFieldEditingChanged:(UITextField *)textField{
    if (textField == self.phoneTF) {
        //手机号
        textField.text = (textField.text.length>11)?[textField.text substringToIndex:11]:textField.text;
        if (self.checked == NO) {
            self.actionBtn.selected = (textField.text.length >= 11)?YES:NO;
        }
    }else{
        //验证码
        
    }
}

//下一步、保存
-(void)saveButtonAction:(UIButton *)sender{
    if (self.checked == NO) {
        if ([self.phoneTF.text isEqualToString:self.currentPhone]) {
            //验证通过
            self.checked = YES;
            self.titleLabel1.text = @"请输入您的手机号";
            self.phoneTF.text = @"";
            self.titleLabel2.hidden = NO;
            self.codeTF.hidden = NO;
            self.actionBtn.selected = YES;
            [self.actionBtn setTitle:@"保存" forState:UIControlStateNormal];
            
        }else{
            [TooltipView showMessage:@"手机号输入不正确" offset:0];
        }
        
    }else{
        //保存
        NSString *phone = (self.phoneTF.text.length>0)?self.phoneTF.text:@"";
        NSString *code = (self.codeTF.text.length>0)?self.codeTF.text:@"";
        [RequestUtil bodayPOST:@"/patient/updatePhone" parameters:@{@"id":kUserId,@"phone":phone,@"smsCode":code,@"smsId":self.smsid} header:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                [TooltipView showMessage:@"保存成功" offset:0];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            
        }];
    }
}



#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.title = @"更换手机号";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleLabel1 = [UILabel lableWithText:@"" colorString:@"#282828" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    self.titleLabel1.frame = CGRectMake(viewPix(16), viewPix(27), Screen_W-viewPix(32), viewPix(24));
    [self.view addSubview:self.titleLabel1];
    [self.view addSubview:self.phoneTF];
    
    self.titleLabel2 = [UILabel lableWithText:@"请输入验证码" colorString:@"#282828" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    self.titleLabel2.frame = CGRectMake(viewPix(16), viewPix(137), Screen_W-viewPix(32), viewPix(24));
    self.titleLabel2.hidden = YES;
    [self.view addSubview:self.titleLabel2];
    [self.view addSubview:self.codeTF];
    [self.codeTF addSubview:self.codeBtn];
    
    self.actionBtn = [UIButton buttonWithTitle:@"下一步" titleFont:LGFontWeight(18, UIFontWeightSemibold) textColor:@"#FFFFFF" frame:CGRectMake(viewPix(16), Screen_H-topBarHeight-viewPix(88), Screen_W-viewPix(32), viewPix(44))];
    [self.actionBtn setBackgroundColor:@"#BCB6FA" selectColor:kThemeColor];
    self.actionBtn.cornerRidus = viewPix(22);
    [self.actionBtn addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.actionBtn];
    
}

-(UITextField *)phoneTF{
    if(!_phoneTF){
        _phoneTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(60), Screen_W-viewPix(32), viewPix(56))];
        _phoneTF.backgroundColor = [UIColor colorWithString:@"#F2F1F8"];
        _phoneTF.tintColor = [UIColor colorWithString:@"#282828"];
        _phoneTF.textColor = [UIColor colorWithString:@"#282828"];
        _phoneTF.textAlignment = NSTextAlignmentLeft;
        _phoneTF.keyboardType = UIKeyboardTypePhonePad;
        _phoneTF.placeholder = @"请输入";
        _phoneTF.cornerRidus = viewPix(28);
        _phoneTF.font = LGFontWeight(16, UIFontWeightMedium);
        _phoneTF.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(16), viewPix(56))];
        _phoneTF.leftViewMode = UITextFieldViewModeAlways;
        [_phoneTF addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _phoneTF;
}

-(UITextField *)codeTF{
    if(!_codeTF){
        _codeTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(173), Screen_W-viewPix(32), viewPix(56))];
        _codeTF.backgroundColor = [UIColor colorWithString:@"#F2F1F8"];
        _codeTF.tintColor = [UIColor colorWithString:@"#282828"];
        _codeTF.textColor = [UIColor colorWithString:@"#282828"];
        _codeTF.textAlignment = NSTextAlignmentLeft;
        _codeTF.keyboardType = UIKeyboardTypePhonePad;
        _codeTF.placeholder = @"请输入";
        _codeTF.cornerRidus = viewPix(28);
        _codeTF.hidden = YES;
        _codeTF.font = LGFontWeight(16, UIFontWeightMedium);
        _codeTF.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(16), viewPix(56))];
        _codeTF.leftViewMode = UITextFieldViewModeAlways;
        [_codeTF addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _codeTF;
}

-(UIButton *)codeBtn{
    if(!_codeBtn){
        _codeBtn = [UIButton buttonWithTitle:@"获取验证码" titleFont:LGFont(14) normalColor:kThemeColor selectColor:@"#61616D"];
        _codeBtn.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(100), 0, viewPix(100), viewPix(56));
        [_codeBtn addTarget:self action:@selector(getSmsCodeAction:) forControlEvents:UIControlEventTouchUpInside];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, viewPix(18), 1, viewPix(20))];
        lineView.backgroundColor = [UIColor colorWithString:@"#D4D3D9"];
        [_codeBtn addSubview:lineView];
    }
    return _codeBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
